#!/bin/bash
################################################################
# Rest API Client                                              #
# Author: Chen GuangQi
#   Date: 2022/01/24
################################################################
CURL='curl -s -q'

SERVER_HOSTNAME=${SERVER_HOSTNAME:-localhost}
SERVER_PORT=${SERVER_PORT:-8080}
BASE_PATH=http://${SERVER_HOSTNAME}:${SERVER_PORT}/RestDemo/rest
COMMON_HEADERS='X-Requested-With:XMLHttpRequest,Accept:application/json'

if [[ $# -lt 1 ]]
then
    cat <<EOF
    Usage: ${0} {GET|POST|PUT|DELETE|OPTIONS|HEAD|TRACE} <resource_path> [query|body] [curl-options]
EOF
    exit 1
fi

## <method> <path> [body|query]
send_request() {
    local method="${1}"
    local uri="${BASE_PATH}${2}"
    local data="${3}"
    shift 3

    case ${method} in
	GET|DELETE)
            eval ${CURL} -X${method} -H{${COMMON_HEADERS}} "${uri}${data:+?${data}}" $@
            ;;
	POST|PUT)
            COMMON_HEADERS+=',Content-Type:application/json'
            eval ${CURL} -X${method} -H{${COMMON_HEADERS}} -d "'${data}'" "${uri}" $@
            ;;
	OPTIONS|HEAD|TRACE)
            eval ${CURL} -X${method} -H{${COMMON_HEADERS}} "${uri}${data:+?${data}}" $@
            ;;
	*)
            cat <<EOF
    Usage: ${0} {GET|POST|PUT|DELETE|OPTIONS|HEAD|TRACE} <resource_path> [query|body] [curl-options]
EOF
            exit 1
            ;;
    esac
}

send_request "$@"
